package repositories

import (
	"blog-backend/internal/app/models"
	"blog-backend/pkg/database"

	"gorm.io/gorm"
)

type PostRepository struct{}

func (r *PostRepository) Exists(postID uint) bool {
	panic("unimplemented")
}

func NewPostRepository() *PostRepository {
	return &PostRepository{}
}

// Create 创建文章
func (r *PostRepository) Create(post *models.Post) error {
	return database.DB.Create(post).Error
}

// Update 更新文章
func (r *PostRepository) Update(post *models.Post) error {
	return database.DB.Save(post).Error
}

// Delete 删除文章
func (r *PostRepository) Delete(id uint) error {
	return database.DB.Delete(&models.Post{}, id).Error
}

// GetByID 通过ID获取文章
func (r *PostRepository) GetByID(id uint) (*models.Post, error) {
	var post models.Post
	result := database.DB.Preload("User").Preload("Category").Preload("Tags").Preload("Comments").First(&post, id)
	if result.Error != nil {
		return nil, result.Error
	}
	return &post, nil
}

// GetBySlug 通过Slug获取文章
func (r *PostRepository) GetBySlug(slug string) (*models.Post, error) {
	var post models.Post
	result := database.DB.Preload("User").Preload("Category").Preload("Tags").Preload("Comments").Where("slug = ?", slug).First(&post)
	if result.Error != nil {
		return nil, result.Error
	}
	return &post, nil
}

// GetPublishedPosts 获取已发布的文章列表（分页）
func (r *PostRepository) GetPublishedPosts(offset, limit int) ([]models.Post, int64, error) {
	var posts []models.Post
	var total int64

	// 获取已发布文章总数
	if err := database.DB.Model(&models.Post{}).Where("status = 1").Count(&total).Error; err != nil {
		return nil, 0, err
	}

	// 获取分页数据
	result := database.DB.Preload("User").Preload("Category").Preload("Tags").
		Where("status = 1").
		Order("published_at DESC").
		Offset(offset).Limit(limit).
		Find(&posts)

	if result.Error != nil {
		return nil, 0, result.Error
	}

	return posts, total, nil
}

// GetPostsByCategory 获取分类下的文章
func (r *PostRepository) GetPostsByCategory(categoryID uint, page, limit int) ([]models.Post, int64, error) {
	var posts []models.Post
	var total int64

	offset := (page - 1) * limit

	// 获取分类下的文章总数
	if err := database.DB.Model(&models.Post{}).Where("category_id = ? AND status = 1", categoryID).Count(&total).Error; err != nil {
		return nil, 0, err
	}

	// 获取分页数据
	result := database.DB.Preload("User").Preload("Category").
		Where("category_id = ? AND status = 1", categoryID).
		Order("published_at DESC").
		Offset(offset).Limit(limit).
		Find(&posts)

	if result.Error != nil {
		return nil, 0, result.Error
	}

	return posts, total, nil
}

// GetPostsByUser 获取用户发布的文章
func (r *PostRepository) GetPostsByUser(userID uint, page, limit int) ([]models.Post, int64, error) {
	var posts []models.Post
	var total int64

	offset := (page - 1) * limit

	// 获取用户文章总数
	if err := database.DB.Model(&models.Post{}).Where("user_id = ?", userID).Count(&total).Error; err != nil {
		return nil, 0, err
	}

	// 获取分页数据
	result := database.DB.Preload("Category").
		Where("user_id = ?", userID).
		Order("created_at DESC").
		Offset(offset).Limit(limit).
		Find(&posts)

	if result.Error != nil {
		return nil, 0, result.Error
	}

	return posts, total, nil
}

// SlugExists 检查Slug是否存在
func (r *PostRepository) SlugExists(slug string) bool {
	var count int64
	database.DB.Model(&models.Post{}).Where("slug = ?", slug).Count(&count)
	return count > 0
}

// IncrementViewCount 增加文章浏览量
func (r *PostRepository) IncrementViewCount(id uint) {
	database.DB.Model(&models.Post{}).Where("id = ?", id).UpdateColumn("view_count", gorm.Expr("view_count + ?", 1))
}

// AddTagToPost 为文章添加标签
func (r *PostRepository) AddTagToPost(postID, tagID uint) error {
	return database.DB.Exec("INSERT INTO post_tags (post_id, tag_id) VALUES (?, ?)", postID, tagID).Error
}

// RemoveTagFromPost 从文章移除标签
func (r *PostRepository) RemoveTagFromPost(postID, tagID uint) error {
	return database.DB.Exec("DELETE FROM post_tags WHERE post_id = ? AND tag_id = ?", postID, tagID).Error
}

// GetTagsForPost 获取文章的标签
func (r *PostRepository) GetTagsForPost(postID uint) ([]models.Tag, error) {
	var tags []models.Tag
	result := database.DB.Joins("JOIN post_tags ON post_tags.tag_id = tags.id").
		Where("post_tags.post_id = ?", postID).
		Find(&tags)
	return tags, result.Error
}
